import CryptoJS from "crypto-js";

export class AesEncryption {
    // 密钥
    #SECRET_KEY = CryptoJS.enc.Utf8.parse('7rSHQFADyQLriczq');
    // // 偏移量
    #iv = CryptoJS.enc.Utf8.parse("7rSHQFADyQLriczq");

    // 加密
    encrypt(word) {
        let encrypted = "";
        if (typeof word == "string") {
            encrypted = CryptoJS.AES.encrypt(word, this.#SECRET_KEY, {
                iv: this.#iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
        } else if (typeof word == "object") {
            //对象格式的转成json字符串
            const data = JSON.stringify(word);
            encrypted = CryptoJS.AES.encrypt(data, this.#SECRET_KEY, {
                iv: this.#iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
        }
        return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
    }

    // 解密
    decrypt(word) {
        const decrypt = CryptoJS.AES.decrypt(word, this.#SECRET_KEY, {
            iv: this.#iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return CryptoJS.enc.Utf8.stringify(decrypt)
    }
}